package cn.wolfcode.mq;

import cn.wolfcode.service.ISeckillProductService;
import cn.wolfcode.web.msg.SeckillCodeMsg;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

/***
 *消费topic为：ORDER_PEDDING_TOPIC的orderMessage类型的消息
 */
@Component
@RocketMQMessageListener(consumerGroup="orderMessageConsumer",
                            topic = MQConstant.ORDER_PEDDING_TOPIC)
public class SeckillOrderMessageListener implements RocketMQListener<OrderMessage> {

    @Autowired
    private ISeckillProductService seckillProductService;
    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    @Override
    public void onMessage(OrderMessage orderMessage) {
        Integer time = orderMessage.getTime();
        Long seckillId = orderMessage.getSeckillId();
        Long userPhone = orderMessage.getUserPhone();
        String token = orderMessage.getToken();
        //封装这一次成功或者失败消息到指定的MQ中的topic;注意tag用于区分
        OrderMQResult orderMQResult = new OrderMQResult();
        orderMQResult.setTime(time);
        orderMQResult.setSeckillId(seckillId);
        orderMQResult.setToken(token);
        String tag="";
        try {
//            int i=1/0;//模拟秒杀下单过程中出现的错误
            //秒杀功能：对应表中库存-1；插入创建的订单；缓存已抢购的痕迹.
            String orderNo = seckillProductService.doSeckill(seckillId, time.longValue(), userPhone);
            tag=MQConstant.ORDER_RESULT_SUCCESS_TAG;
            orderMQResult.setOrderNo(orderNo);
            //发送延迟消息(如果订单抢到了，但在规定时间内并未支付则需要我们进行一个逻辑处理)
            //封装消息：用之前秒杀成功的消息orderResult
            MessageBuilder<OrderMQResult> orderMQResultMessageBuilder = MessageBuilder.withPayload(orderMQResult);
            rocketMQTemplate.syncSend(MQConstant.ORDER_PAY_TIMEOUT_TOPIC,
                    orderMQResultMessageBuilder.build(),3000,15);//延迟等级为2，5s
        } catch (Exception e) {//失败（比如真实库存不足等等），也需要封装一个消息
            e.printStackTrace();
            orderMQResult.setCode(SeckillCodeMsg.SECKILL_STOCK_OVER.getCode());
            orderMQResult.setMsg(SeckillCodeMsg.SECKILL_STOCK_OVER.getMsg());
            tag=MQConstant.ORDER_RESULT_FAIL_TAG;
        }
        //发送封装的orderMQResult消息（失败或者成功tag）到指定MQ的topic
        rocketMQTemplate.sendOneWay(MQConstant.ORDER_RESULT_TOPIC+":"+tag,orderMQResult);//也不在意回调
    }
}
